package edu.wtbu.cs.androiddemo.activity;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.room.Room;

import java.util.List;

import edu.wtbu.cs.androiddemo.R;
import edu.wtbu.cs.androiddemo.sqlite.room.AppDatabase;
import edu.wtbu.cs.androiddemo.sqlite.room.User;
import edu.wtbu.cs.androiddemo.sqlite.room.UserDao;


/**
 * Room 是基于SQLite ORM框架
 *
 *
 */
public class RoomSampleActivity extends AppCompatActivity {
    String logTag = RoomSampleActivity.class.getName();

    AppDatabase  db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_room_sample);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        //需要配置allowMainThreadQueries，
        // 否则Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
        db = Room.databaseBuilder(getApplicationContext(),
                AppDatabase.class, "database-name").allowMainThreadQueries().build();

        UserDao userDao = db.userDao();
        User user =new User();
        user.setFirstName("chende");
        user.setLastName("de");
        userDao.insertAll(user);
        List<User> users = userDao.getAll();
        Log.i(logTag,users.toString());
        db.close();
        TextView textView = findViewById(R.id.user_info_tv);
        textView.setText(users.toString());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        db.close();
    }
}